#include "CTableServiceState.h"
#include <QDebug>

#define KEY_CURREN_USER "CurrentUser"
#define KEY_SCREEN_STATE "ScreenState"
#define KEY_MDM_LOCKED "MdmLocked"
#define KEY_MDM_ACTIVE "MdmActive"
#define KEY_MDM_PASSWD_POLICIES "MdmPasswdPolicies"

CTableServiceState::CTableServiceState(QObject *parent)
    : AbstractTable{"User",parent}
{
    QString createSql = "CREATE TABLE ServiceState ("
        "    [Key] TEXT PRIMARY KEY"
        "               UNIQUE"
        "               NOT NULL,"
        "    Value TEXT"
        ");";

    if(!exists()){
        createTable(createSql);
        init();
    }
}

CTableServiceState *CTableServiceState::getInstance()
{
    static CTableServiceState* pInstance = nullptr;
    if(nullptr == pInstance){
        pInstance = new CTableServiceState();
    }
    return pInstance;
}

void CTableServiceState::setCurrentUser(const QString &userId)
{
    AbstractTable::updateColumn("Key",KEY_CURREN_USER,"Value",userId);
}

QString CTableServiceState::currentUser()
{
    return AbstractTable::queryColumn("Key",KEY_CURREN_USER,"Value").toString();
}

void CTableServiceState::setScreenState(const int &state)
{
    AbstractTable::updateColumn("Key",KEY_SCREEN_STATE,"Value",state);
}

int CTableServiceState::screenState()
{
    return AbstractTable::queryColumn("Key",KEY_SCREEN_STATE,"Value").toInt();
}

void CTableServiceState::setMdmLocked(const bool locked)
{
    AbstractTable::updateColumn("Key",KEY_MDM_LOCKED,"Value",locked);
}

bool CTableServiceState::mdmLocked()
{
    return AbstractTable::queryColumn("Key",KEY_MDM_LOCKED,"Value").toBool();
}

void CTableServiceState::setMdmActive(const bool active)
{
    AbstractTable::updateColumn("Key",KEY_MDM_ACTIVE,"Value",active);
}

bool CTableServiceState::mdmActive()
{
    return AbstractTable::queryColumn("Key",KEY_MDM_ACTIVE,"Value").toBool();
}

void CTableServiceState::setMdmPasswdPolicies(const int &policies)
{
    AbstractTable::updateColumn("Key",KEY_MDM_PASSWD_POLICIES,"Value",policies);
}

int CTableServiceState::mdmPasswdPolicies()
{
    return AbstractTable::queryColumn("Key",KEY_MDM_PASSWD_POLICIES,"Value").toInt();
}

void CTableServiceState::init()
{
    qInfo() << "init table rows.";
    QMap<QString,QString> map;
    map.insert(KEY_CURREN_USER,"0");
    map.insert(KEY_SCREEN_STATE,"0");
    map.insert(KEY_MDM_LOCKED,"0");
    map.insert(KEY_MDM_ACTIVE,"0");
    map.insert(KEY_MDM_PASSWD_POLICIES,"0");

    foreach (QString key, map.keys()) {
        QVariantMap varMap;
        varMap.insert("Key",key);
        varMap.insert("Value",map[key]);

        bool ok = AbstractTable::addRow(varMap);
        if(!ok){
            qWarning() << "addRow failed! key:" << key << " val:" << map[key];
        }
    }
}
